package com.microservice.skeleton.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservice.skeleton.common.vo.Result;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: lijin
 * @date: 2018年09月26日
 */
public class OAuth2AccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8;");
        PrintWriter writer = response.getWriter();

        writer.println(new ObjectMapper().writeValueAsString(Result.failure(500,ExceptionUtils.getRootCauseMessage(accessDeniedException))));
        response.flushBuffer();
    }
}
